﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WikiMiner;
using Graphs;
using System.Drawing;

namespace WindowsFormsApplication1
{
    class SearchContext2Way : SearchContext
    {
        public SearchContext2Way(Article from, Article to, float relAdd, float relLink)
            : base(from, to)
        {
            this.relAdd = relAdd;
            this.relLink = relLink;

            Graph = new Graph();

            var f = Graph.AddNode(new WikiVisNode()
            {
                text = from.title,
                fixedinplace = false,
                h = Relatedness.Get(from.title, to.title)
            });

            var t = Graph.AddNode(new WikiVisNode()
            {
                text = to.title,
                fixedinplace = false,
                h = Relatedness.Get(to.title, from.title)
            });

            // make sure they don't drift miles apart
            Graph.AddLink(new WikiVisLink() { a = t, b = f, visible = false, force_when_visible = true, strength = 0.2f });


        }

        private new List<Candidate2Way> open = new List<Candidate2Way>();

        public SearchContext2Way(Article from, Article to)
        {
            this.From = from;
            this.To = to;

            open.Add(new Candidate2Way() { article = from, destination = to, parent = null, visitedbyfrom = true });
            open.Add(new Candidate2Way() { article = to, destination = from, parent = null, visitedbyto = true });         
            
        }

        public bool Step()
        {
            if (Compelete)
                return true;

            if (open.Count == 0)
                return Compelete = true;

            Iterations++;

            Candidate2Way at = open.OrderBy(item => item.f).First();

            if (at.visitedbyto && at.visitedbyfrom)
            {
                // set path

                Path = at.Path;

                return Compelete = true;
            }
            else
            {
                List<Article> path = new List<Article>();

                for (var p = at; p != null; p = p.parent)
                    path.Add(p.article);

                path.Reverse();

                this.Path = path.ToArray();
            }


            closed.Add(at.article);
            open.Remove(at);

            //Recolour();

            Node node_at = null;
            Graph g = Graph;

            if (g != null)
            {
                node_at = g.GetNode(at.article.title);

                node_at.visible = true;

                if (at.parent != null)
                {
                    g.GetLink(node_at, g.GetNode(at.parent.article.title)).visible = true;

                }
                Candidate2Way at2 = at;

                while (at2 != null)
                {
                    g.GetNode(at2.article.title).color = Color.Salmon;

                    if (at.parent != null)
                        g.GetLink(g.GetNode(at.article.title), g.GetNode(at.parent.article.title)).color = Color.Red;

                    at2 = at2.parent;
                }
            }

            IEnumerable<Links.LinksResult> toCheck;

            if (at.visitedbyfrom)  // we came from from... check outlinks
            {
                toCheck = Links.GetOutLinks(at.article.id);
            }
            else
            {
                toCheck = Links.GetInLinks(at.article.id);
            }

            foreach (var link in toCheck)
            {
                float rel = Relatedness.Get(at.article.title, link.title);

                Node node_to = null;

                if (g != null)
                {
                    node_to = g.GetNode(link.title);

                    if (node_to == null)
                    {
                        node_to = new WikiVisNode() { text = link.title, visible = false };
                        g.AddNode(node_to, node_at);
                    }

                    if (rel > relAdd)
                        node_to.visible = true;

                    Link l = g.AddLink(new WikiVisLink() { a = node_at, b = node_to, visible = false, rel = rel });

                    if (at.visitedbyfrom)
                    {
                        l.AddArrowTo(node_to);
                    }
                    else
                    {
                        l.AddArrowTo(node_at);
                    }
                    
                    l.width = 10 * rel;

                    if (rel > relLink)
                    {
                        l.visible = true;
                    }
                }

                if (!closed.Exists(item => item.id == link.id))
                {
                    Candidate2Way existing = open.FirstOrDefault(item => item.article.id == link.id);

                    if (existing != null)
                    {
                        if (
                            (at.visitedbyto && existing.visitedbyfrom) ||
                            (at.visitedbyfrom && existing.visitedbyto)
                            )
                        {

                            // path here.
                        }
                        else
                        {
                            existing.UpdateParentIfBetter(at);
                        }
                    }
                    else
                    {
                        existing = new Candidate2Way()
                        {
                            article = link,
                            parent = at
                        };
                        open.Add(existing);
                    }

                    if (g != null)
                    {
                        (node_to as WikiVisNode).g = existing.G;
                        (node_to as WikiVisNode).h = existing.H;
                    }
                }
            }


            return false;
        }



        protected class Candidate2Way 
        {
            public bool visitedbyfrom;
            public bool visitedbyto;

            public Article article;
            public Article destination;

            public float G;
            public float H;
            public float f;

            public Article[] Path;

            public void Calc()
            {
                H = (1 - Relatedness.Get(article.title, destination.title));
                if (H == 1)
                    H = 1000;


                f = G + H;
            }


            private Candidate2Way _parent = null;

            public Candidate2Way parent
            {
                set
                {
                    _parent = value;
                    if (value == null)
                    {
                        G = 0;
                    }
                    else
                    {
                        G = _parent.G + 1 - Relatedness.Get(article.title, _parent.article.title);
                        destination = parent.destination;
                    }
                    Calc();
                }
                get
                {
                    return _parent;
                }
            }

            internal void UpdateParentIfBetter(Candidate2Way newparent)
            {
                if (_parent != null)
                {
                    if (_parent.G + 1 - Relatedness.Get(article.title, newparent.article.title) < G)
                    {
                        parent = newparent;
                    }
                }
            }
        }       
    }
}
